﻿//***********************
//* 感谢 https://github.com/durow/UEditorNetCore
//***********************
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using QW.Core.Log;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace QW.UEditor
{
    /// <summary>
    /// ueditor构建器
    /// </summary>
    public static class UEditorBuilder
    {
        /// <summary>
        /// 添加Ueditor
        /// </summary>
        /// <param name="service"></param>
        /// <returns></returns>
        public static void AddUEditor(this IServiceCollection service)
        {
            var actions = new ActionCollection();
            service.AddSingleton(actions);
            service.AddSingleton<UEditorService>();
        }
        /// <summary>
        /// 使用UEditor
        /// </summary>
        /// <param name="app"></param>
        /// <param name="saveFileRootPath"></param>
        /// <param name="configFile"></param>
        /// <param name="isLocalConfig"></param>
        /// <param name="isUseMiddleware">是否使用中间件</param>
        /// <param name="mapName">中间件映射名</param>
        /// <returns></returns>
        public static ActionCollection UseUEditor(
            this IApplicationBuilder app,
            string saveFileRootPath,
            string configFile = "config.json",
            bool isLocalConfig = false,
            bool isUseMiddleware=true,
            string mapName = "/UEditor")
        {
            Config.ConfigFile = configFile;
            Config.IsLocalConfig = isLocalConfig;
            Config.SaveFileRootPath = saveFileRootPath;
            if (isUseMiddleware)
            {
                app.Map(mapName, UEditorHandle);
            }
            var actions = (ActionCollection)app.ApplicationServices.GetService(typeof(ActionCollection));
            return actions;
        }
        /// <summary>
        /// 中间件
        /// </summary>
        /// <param name="app"></param>
        private static void UEditorHandle(IApplicationBuilder app)
        {
            app.Run(context =>
            {
                //启动倒带方式
                context.Request.EnableBuffering();
                var ser = (UEditorService)app.ApplicationServices.GetService(typeof(UEditorService));
                ser.DoAction(context);
                return Task.CompletedTask;
            });
        }
    }
}
